package com.mspbots.core.system;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mspbots.core.AbstractBaseController;
import com.mspbots.core.RestServerException;
import com.mspbots.core.system.model.SystemConfiguration;
import com.mspbots.core.system.service.SystemConfigurationService;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.Callable;

@RestController
@RequestMapping("system-configuration")
public class SystemConfigurationController extends AbstractBaseController<SystemConfiguration, SystemConfigurationService> {

    @GetMapping(path = "keyword/{keyword}")
    public Callable<SystemConfiguration> selectByKey(@PathVariable String keyword) {
        return () -> service.selectByKeyword(keyword);
    }

    @Override
    @PostMapping
    public Callable insert(@RequestBody SystemConfiguration entity) {
        return () -> {
            int count = service.count(Wrappers.<SystemConfiguration>lambdaQuery()
                    .eq(SystemConfiguration::getKeyword, entity.getKeyword()));
            if (count > 0) {
                throw new SystemConfigExistsException(500, "This system configuration key world exists.");
            }
            service.saveOrUpdate(entity);
            return entity;
        };
    }

    static class SystemConfigExistsException extends RestServerException {

        public SystemConfigExistsException(int code, String msg) {
            super(code, msg);
        }
    }

}
